// Modules to control application life and create native browser window
const { app, BrowserWindow, ipcMain, dialog } = require("electron");
const path = require("path");
const { exec, fork } = require("child_process");
const fs = require("fs");
const internalIp = require("internal-ip");
const QR = require("qrcode");

let child;

function createWindow() {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, "preload.js"),
      contextIsolation: false,
      nodeIntegration: true,
    },
  });

  // and load the index.html of the app.
  mainWindow.loadFile("index.html");

  // Open the DevTools.
  // mainWindow.webContents.openDevTools();
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  createWindow();

  app.on("activate", function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });
});

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on("window-all-closed", function () {
  console.log("close");
  closeDir();
  if (process.platform !== "darwin") app.quit();
});

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
ipcMain.on("chooseDir", async function (event, p) {
  if (child) {
    child.kill("SIGINT");
  }
  let result = await dialog.showOpenDialog({
    properties: ["openDirectory"],
  });

  if (!result.canceled && result.filePaths && result.filePaths.length) {
    let qrcode;
    let dir = result.filePaths[0];
    let files = getFiles(dir);
    let localip = internalIp.v4.sync();
    let prefix = `http://${localip}:3000`;
    console.log({ dir, files });
    // child = exec(`npx http-server ${dir} -p 1218`);
    child = fork(path.join(__dirname, "./web.js"), [
      JSON.stringify({ prefix, dir, files }),
    ]);
    // child.on("message", (msg) => {
    //   console.log(msg);
    // });
    // child.stdout.on("data", function (data) {
    //   console.log("#" + data + "#");
    // });
    // child.unref();
    qrcode = await new Promise((resolve) => {
      QR.toDataURL(`${prefix}/list`, (err, url) => {
        resolve(url);
      });
    });
    console.log(qrcode, typeof qrcode);
    event.reply("onQrcode", qrcode);
  }
});

ipcMain.on("closeDir", function () {
  closeDir();
});

process.on("exit", () => {
  console.log("process exit");
  closeDir();
});

const closeDir = () => {
  if (child) {
    console.log("child closing...");
    child.kill("SIGINT");
  }
};

const getFiles = (dir) => {
  let arr = fs
    .readdirSync(dir, { encoding: "utf-8" })
    .filter((n) => fs.statSync(`${dir}\\${n}`).isFile());
  console.log(arr);
  return arr;
};
